<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <!-- 自定义属性 data- <route-link to="">  data-id dataset.to -->
      <a href="javascript:;" data-to="/address">首页</a>
      <a href="javascript:;" data-to="/info">物品</a>
      <a href="javascript:;" data-to="/login">每个</a>
    </div>
    <div class="content"></div>

    <script>
      // history必须配合后台使用 404 如何解决history路由下页面刷新404问题
      // pushState  popState load

      class HistoryRouter {
        constructor({ routes }) {
          this.routes = routes
          this.content = document.querySelector('.content')
          //
          this.aDom = document.querySelectorAll('a')

          this.init()
        }
        init() {
          this.aDom.forEach((item) => {
            item.onclick = () => {
              let pathItem = item.dataset.to
              console.log('pathItem:', pathItem)
              // 给浏览器的历史记录添加栈数据    []  [{}]
              window.history.pushState({}, null, pathItem)

              let pathname = window.location.pathname

              let template = this.routes.filter((v) => v.path === pathname)
              console.log('template: ', template)
              this.content.innerHTML = template[0].component
            }
          })
          // 跳转时候调用 pop()
          window.addEventListener('popstate', () => {
            console.log(window.location.pathname)
            let pathname = window.location.pathname
            let template = this.routes.filter((v) => v.path === pathname)
            this.content.innerHTML = template[0].component
          })

          // 刷新调用
          window.addEventListener('load', () => {
            console.log(window.location.pathname)
            let pathname = window.location.pathname
            let template = this.routes.filter((v) => v.path === pathname)

            this.content.innerHTML = template[0].component
          })
        }
      }

      new HistoryRouter({
        routes: [
          {
            path: '/address',
            component: '<div>Address</div>',
          },
          {
            path: '/info',
            component: '<div>info</div>',
          },
          {
            path: '/login',
            component: '<div>login</div>',
          },
        ],
      })
    </script>
  </body>
</html>
